package com.game;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

//图片处理类
public class SplitImage {

	//游戏图片
	private static BufferedImage image;
	
	//拼图集合
	public static List<Map<String,Object>> smallImageList;
	
	//加载图片
	public static BufferedImage loadImage(String path){
		try {
			FileInputStream filein=new FileInputStream(new File(path));
			image=ImageIO.read(filein);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return image;
	}
	//加载图片 方法重载
	public static BufferedImage loadImage(InputStream is){
		try {
			image=ImageIO.read(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return image;
	}
	
	//缩放图片到合适尺寸
	public static BufferedImage reSizeImage(int rowNum,int colNum,int width,int height){

		BufferedImage img=new BufferedImage(GameConstant.IMG_CONS_WIDTH,GameConstant.IMG_CONS_HEIGHT,image.getType());
		Graphics gh=img.getGraphics();
		gh.drawImage(image, 0, 0, GameConstant.IMG_CONS_WIDTH,GameConstant.IMG_CONS_HEIGHT, null);
		gh.dispose();
		return img;
	}
	//缩放图片 方法重载
	public static BufferedImage reSizeImage(){

		BufferedImage img=new BufferedImage(GameConstant.IMG_CONS_WIDTH,GameConstant.IMG_CONS_HEIGHT,image.getType());
		Graphics gh=img.getGraphics();
		gh.drawImage(image, 0, 0, GameConstant.IMG_CONS_WIDTH,GameConstant.IMG_CONS_HEIGHT, null);
		gh.dispose();
		return img;
	}
	
	/**
	 * 根据行和列拆分图片
	 * @param rowNum 拼图板行数
	 * @param colNum 拼图板列数
	 * @param width  图片宽度
	 * @param height 图片高度
	 * @return
	 */
	public static List<Map<String,Object>> splitImage(int rowNum,int colNum,int width,int height){
		//根据参数创建指定长度的集合
		smallImageList=new ArrayList<Map<String,Object>>();
		
		image=reSizeImage(rowNum, colNum, width, height);
		width=image.getWidth()/colNum;
		height=image.getHeight()/rowNum;
		
		int i=0;//保存正常顺序0-11
		//外层循环遍历行
		for(int y=0;y<rowNum;y++){ // Y方向↓
			//内层循环遍历列
			for(int x=0;x<colNum;x++){//X方向→
				BufferedImage img=image.getSubimage(x*width, y*height, width, height);
				Map<String,Object> item=new HashMap<String,Object>();//每个元素，保存索引和图片
				item.put("index", i);
				item.put("image", img);
				smallImageList.add(item);
				i=i+1;
			}
		}
		
		return smallImageList;
	}
	
	
	//随机生成顺序
	public static List<Map<String,Object>> randomImageList(){
		//1.打乱 overList 
		Collections.shuffle(smallImageList);
		return smallImageList;
	}
	
	
	
}
